# -*- coding: utf-8 -*-

from osv import fields,osv
from osv.orm import browse_record
import tools
from functools import partial
import pytz
import pooler
from tools.translate import _
from service import security
import netsvc
import datetime

class aas_generate_week(osv.TransientModel):
    _name = 'aas.generate.week'
    _columns = {
        'semester': fields.many2one('aas.academic.semester', string='Học kỳ', readonly=True),
        'prefix': fields.char('Tiền tố', size=64, help='Tiền tố sẽ được gắn phía trước STT của tuần.'),
        'from_no': fields.integer('STT bắt đầu', required=True),
        'to_no': fields.integer('STT kết thúc', required=True),
        'date_from': fields.date('Ngày bắt đầu', required=True),
    }
    
    def default_get(self, cr, uid, fields, context=False):
        res = super(aas_generate_week, self).default_get(cr, uid, fields, context=context)
        semester_id = context.get('active_id', False)
        res.update({'semester': semester_id})
        return res
    
    def generate_week(self, cr, uid, ids, context=False):
        obj = self.browse(cr, uid, ids[0], context=context)
        if obj:
            week_obj = self.pool.get('aas.academic.week')
            semester_obj = self.pool.get('aas.academic.semester')
            year_obj = self.pool.get('aas.academic.year')
            
            semester_id = obj.semester.id
            year_id = obj.semester.academic_year.id
            prefix = obj.prefix or ''
            from_no = obj.from_no or 0
            to_no = obj.to_no or -1
            date_from = obj.date_from or False
            date_from_obj = datetime.datetime.strptime(date_from, '%Y-%m-%d').date()
            week_delta = datetime.timedelta(weeks = 1)
            days_delta = datetime.timedelta(days = 6)
            
            if date_from_obj.weekday() != 0:
                raise osv.except_osv(_('Lỗi!'), _('Ngày bắt đầu phải là thứ Hai!')) 
            
            i = from_no
            date_start = date_from_obj
            date_end = date_start + days_delta
            
            while i <= to_no:
                week_name = ''
                if prefix:
                    prefix = prefix.strip()
                    week_name += prefix + ' '
                week_name += str(i)
                week_data = {
                    'name': week_name, 
                    'number': i, 
                    'academic_semester': semester_id,
                    'academic_year': year_id,
                    'date_start': date_start.strftime('%Y-%m-%d'),
                    'date_end': date_end.strftime('%Y-%m-%d'),
                }
                
#                try:
                week = week_obj.create(cr, uid, week_data, context=context)
#                except:
#                    raise osv.except_osv(_('Error!'), _('Cannot create weeks in this period! Maybe the name already exists!'))
                i += 1
                date_start += week_delta
                date_end = date_start + days_delta
            
            semester = semester_obj.browse(cr, uid, semester_id, context=context)
            if len(semester.academic_weeks):
                sql = '''
                    SELECT MIN(date_start), MAX(date_end)
                    FROM aas_academic_week
                    WHERE academic_semester = %s
                '''
                cr.execute(sql, (semester_id,))
                if cr.rowcount > 0:
                    (min_date_start, max_date_end) = cr.fetchone()
                    semester_obj.write(cr, uid, [semester.id], {'date_start': min_date_start, 'date_end': max_date_end}, context=context)
            
            if semester.academic_year.id:
                year = year_obj.browse(cr, uid, semester.academic_year.id, context=context)
                if len(year.academic_semesters):
                    sql = '''
                        SELECT MIN(date_start), MAX(date_end)
                        FROM aas_academic_semester
                        WHERE academic_year = %s
                    '''
                    cr.execute(sql, (year.id,))
                    if cr.rowcount > 0:
                        (min_date_start, max_date_end) = cr.fetchone()
                        year_obj.write(cr, uid, [year.id], {'date_start': min_date_start, 'date_end': max_date_end}, context=context)
                        
        return {
            'res_id': obj.semester.id,
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'aas.academic.semester',
            'type': 'ir.actions.act_window',
            'target': 'new',
        }
    
aas_generate_week()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
